<?php
	$searchPlugin = new Plugin('Search Content');
	$searchPlugin->addPlugin( 'search', 'searchContent' );
	$searchPlugin->addPlugin( 'search-box', 'searchBox' );
	$searchPlugin->addPlugin( 'after-class-init', 'testAndRedirect' );
	$searchPlugin->addPlugin( 'styles', 'searchCssFile' );
	$searchPlugin->Author('Ramblingwood, USA');
	$searchPlugin->Description( 'This allows you to seach the content in your database using FULLTEXT.' );
	$searchPlugin->Version( '0.0.3' );
	$searchPlugin->addSidebarBlock('Search', 'searchBox');
	$searchPlugin->addInstall('searchPluginInstall');
	$searchPlugin->addInterface('searchPluginInterface');
	function searchCssFile () {
		global $searchPlugin;
		echo <<<EOT
	<link rel="stylesheet" type="text/css" href="{$searchPlugin->VISUAL_ROOT}plugins/searchContent/searchStyles.css" media="screen"/>

EOT;
	}
	function searchPluginInstall () {
		global $searchPlugin;
		$defaultHTML = <<<EOT
	<div class="searchBox">
		<form id="searchForm" name="searchForm" action="" method="post">
			<input id="searchInput" type="text" name="q" value="{$visSearch}" />
			<input type="submit" class="button" value="Go!" />
		</form>
	</div>
EOT;
		$searchPlugin->addOption('searchBoxHTML', $defaultHTML);
	}
	function searchPluginUninstall () {
		global $searchPlugin;
		$searchPlugin->deleteOption('searchBoxHTML');
	}
	function searchPluginInterface () {
		global $searchPlugin;
		if($_POST['save']) {
			if($searchPlugin->updateOption('searchBoxHTML', $_POST['html']))
				echo $searchPlugin->message('success', 'Settings Saved', 'Woohoo!');
			else
				echo $searchPlugin->message('error', 'Hmmm...Something didn\'t work...', 'Please try again.');
		}
		$html = $searchPlugin->getOption('searchBoxHTML');
		echo <<<EOT
	<form action="{$searchPlugin->VISUAL_ROOT}admin.php?page=plugins&interface=search-content" method="post">
		<fieldset>
			<h2>Search Content Settings</h2>
			<div class="form-row">
				<label for="location">Search Box HTML<span class="small gray">This is the HTML that is shown when plugin('search-box'); is run, and when it shows up in sidebar.</span></label>
				<span>
					<textarea rows="20" cols="50">{$html}</textarea>
				</span>
			</div>
			<div class="form-row form-row-last">
				<label for="save">&nbsp;</label>
				<span>
					<input name='save' value='Save' type="submit" />
				</span>
			</div>
		</fieldset>
	</form>
EOT;
	}
	function findAllOccurences($Haystack, $needle, $limit=0) {
		$Positions = array();
		$currentOffset = 0;
		$count=0;
		while(($pos = strpos($Haystack, $needle, $offset))!==false && ($count < $limit || $limit == 0)) {
			$Positions[] = $pos;
			$offset = $pos + strlen($needle);
			$count++;
		}
		return $Positions;
	}
	function truncate($string, $search, $limit, $break = ".", $pad = "...") {
		$foundArray = findAllOccurences(strtolower($string), strtolower($search));
		$searchTermLength = strlen($search);
		if(count($foundArray) == 0) {
			// return with no change if string is shorter than $limit
			if (strlen($string) <= $limit)
				return $string;
			// is $break present between $limit and the end of the string?
			if (false !== ($breakpoint = strpos($string, $break, $limit))) {
				if ($breakpoint < strlen($string) - 1) {
					$string = substr($string, 0, $breakpoint) . $pad;
				}
			}
			return $string;
		}
		foreach($foundArray as $key => $value) {
			$startSearchSnippet = $value - 40;
			$endSearchSnippet = $searchTermLength + 80;
			$r .= ' ...'.substr($string, $startSearchSnippet, $endSearchSnippet).'...';
		}
		return $r;
		}
	$the_count = 0;
	function highlight_this($text, $words) {
		global $the_count;
		$words = trim($words);
		$wordsArray = explode(' ', $words);
			foreach($wordsArray as $word) {
			 if(strlen(trim($word)) != 0)
			
			 //exclude these words from being replaced
			 $exclude_list = array("word1", "word2", "word3");
			// Check if it's excluded
			if ( in_array( strtolower($word), $exclude_list ) ) {
	   
			} else {
				$text = str_ireplace($word, "<span class=\"searchStringFound\">".strtoupper($word)."</span>", $text, $count);
				$the_count = $count + $the_count;
				}
			   
		}
		//added to show how many keywords were found
	   
		return array($words,$text,$the_count);
	} 
	function searchContent () {
		global $page;
		if(DB_USE == 'mysql') {
			$qry = "SELECT VERSION()";
			$result = $page->db_query($qry);
			$ver = (@mysql_result($result, 0));
			$ver = preg_replace('/[^0-9.]+/', '', $ver);
			$verS = explode('.', $ver);
			if(($verS[1] >= 1) && ($verS[2] >= 7))
				$mysqlDBtrue = true;
			else
				$mysqlDBtrue = false;
			$searchString = $_GET['q'];
			if($mysqlDBTrue ==  false) {
			$sql = "SELECT *,
						MATCH (title,content) AGAINST ('{$searchString}') AS score 
						FROM ".DBTABLEPREFIX."content_pages 
						WHERE
							MATCH (title,content) AGAINST ('{$searchString}') OR menutitle LIKE '%".$searchString."%' ORDER BY score DESC";
			}
			else {
			$sql = "SELECT *,
						MATCH (title,content) AGAINST ('{$searchString}') AS score 
						FROM ".DBTABLEPREFIX."content_pages 
						WHERE
							MATCH (title,content) AGAINST ('{$searchString}') OR menutitle LIKE '%".$searchString."%' IN NATURAL LANGUAGE MODE ORDER BY score DESC";
			}
		}
		else {
			$searchString = $_GET['q'];
			$sql = "SELECT * FROM ".DBTABLEPREFIX."content_pages WHERE content LIKE '%".$searchString."%' OR menutitle LIKE '%".$searchString."%' OR title LIKE '%".$searchString."%'";
		}
		$query = $page->db_query($sql) or die($page->message('error', 'MySQL Error', $page->db->error()));
		$seachResultsContent .= '<div id="searchResults"><ol id="searchResultsOl">';
		$searchResultNumRows = $page->db->numRows($query);
		if($searchResultNumRows == 0) {
			$seachResultsContent = <<<EOT
	<div class="message-warning message">
		<div class="message-header">
			<h3>No results found. Try another search.</h3>
		</div>
		<div class="message-content">
			<p>First, check to make sure you spelled words correctly. Then, try being more generic. For example, try 'cars' instead of 'ford cars'.</p>
		</div>
	</div>
EOT;
		}
		else {
		while($row = $page->db->fetchAssoc($query)) {
			$searchedCount=highlight_this(truncate(strip_html_tags($row['content']), $searchString, 200),$searchString);
			$row['content'] = stripslashes($searchedCount[1]);
			$totalWordCount += $searchedCount[2];
			if($page->getSetting('Clean Urls') == 'Enabled') {
				if(SIMPLE_CLEAN_URLS)
					$searchResultsLink = THEME_URL.$page->make_clean_url($row['menutitle']);
				else
					$searchResultsLink = THEME_URL.$row['id']."/".$page->make_clean_url($row['menutitle']);
			}
			else {
				$searchResultsLink = THEME_URL.'?page='.$row['id'];
			}
			 $seachResultsContent .= <<<EOT
		<li>
			<div class="searchResultsTitle">
				<h3><a href="{$searchResultsLink}">{$row['title']}</a></h3>
			</div>
			<div class="searchResultsContent">
				{$row['content']}
			</div>
		</li>
EOT;
	$count++;
		}
		$summary = "<div class=\"searchResultsOverview\">A search for \"<strong>" . $searchString. "</strong>\" found <strong>" . $totalWordCount . "</strong> exact match(es) in the content. However, <strong>$count</strong> page(s) were found.</div>";
		$seachResultsContent .= '</ol></div>';
		}
		$page->pageTitle("Search results for \"{$searchString}\"");
		$page->pageContent($summary.$seachResultsContent);
	}
	function testAndRedirect () {
		if($_POST['q']) {
			global $page;
			// Clean up by removing unwanted characters
			$qclean = $page->make_clean_url($_POST['q']);
			// Replace single spaces with a URL friendly plus sign
			$qclean = str_replace("-", "+", $qclean);
			// If validation has passed, redirect to the URL rewritten search page
			if ($qclean != '') {
				 header( 'Location: '.THEME_URL.'search/'.$qclean );
			}
			/*if($page->getSetting('Clean Urls') == 'Enabled') {
				$actionUrl = THEME_URL.'search/';
			}
			else {
				$actionUrl = THEME_URL.'?page=search';
			}*/
		}	
	}
	function searchBox () {
		global $page;
		global $searchPlugin;
		$searchString = $_GET['q'];
		$visSearch = str_replace('+', ' ', $searchString);
		echo $searchPlugin->getOption('searchBoxHTML');
	}

?>